package com.chenjt.customizePage;

import com.chenjt.customizePage.imageCode.ImageCode;
import com.chenjt.customizePage.imageCode.ImageCodeGenerator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2025/1/24 9:28
 */
@RestController
public class CustomizePageController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    /**
     * 访问根路径时进入该接口
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public SimpleResponse requireAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws IOException {

        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if(savedRequest != null){
            String targetUrl = savedRequest.getRedirectUrl();
            logger.info("引起跳转的请求是：" + targetUrl);
            if(StringUtils.endsWithIgnoreCase(targetUrl,".html")){
                // 跳转到login.html这个页面
                redirectStrategy.sendRedirect(request,response,"/login.html");
            }
        }

        //  这里会返回这个状态码：@ResponseStatus(code = HttpStatus.UNAUTHORIZED) 401
        return new SimpleResponse("访问的服务需要身份认证，请引导用户到登录页");
    }


    /**
     * 获取当前用户信息 第一种方式
     * @return
     */
    @GetMapping("/getCurrentUser_oneWay")
    public Object getCurrentUser_oneWay(){
        // {"authorities":[{"authority":"ROLE_USER"}],"details":{"remoteAddress":"0:0:0:0:0:0:0:1","sessionId":null},"authenticated":true,"principal":{"password":null,"username":"admin","authorities":[{"authority":"ROLE_USER"}],"accountNonExpired":true,"accountNonLocked":true,"credentialsNonExpired":true,"enabled":true},"credentials":null,"name":"admin"}
        return SecurityContextHolder.getContext().getAuthentication();
    }


    /**
     * 获取当前用户信息 第二种方式
     * @param user
     * @param request
     * @return
     */
    @GetMapping("/getCurrentUser_twoWay")
    public Object getCurrentUser_twoWay(Authentication user, HttpServletRequest request){
        return user;
    }


    /**
     * 获取principal属性
     * @param userDetails
     * @return
     */
    @GetMapping("/getPrincipal")
    public Object getPrincipal(@AuthenticationPrincipal UserDetails userDetails){
        // {"password":null,"username":"admin","authorities":[{"authority":"ROLE_USER"}],"accountNonExpired":true,"accountNonLocked":true,"credentialsNonExpired":true,"enabled":true}
        return userDetails;
    }


    public static final String SESSION_KEY_IMAGE = "SESSION_KEY_IMAGE_CODE";

    HttpSessionSessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    /**
     * 图片验证码
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/code/image")
    public void imageCode(HttpServletRequest request,HttpServletResponse response) throws IOException {
        ImageCode imageCode = ImageCodeGenerator.generate(request);
        // 存储校验码，用于登录时校验，实际根据具体情况去做存储
        sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY_IMAGE,imageCode);
        ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
    }



    public static final String SESSION_KEY_SMS = "SESSION_KEY_SMS_CODE";

    /**
     * 短信验证码
     * @param request
     * @param response
     */
    @GetMapping("/code/sms")
    public void mobileCode(HttpServletRequest request,HttpServletResponse response){

        String mobile = request.getParameter("mobile");
        // 发送短信
        String mobileCode = "3333";
        // 校验码过期时间是60秒
        ImageCode imageCode = new ImageCode(mobileCode, 60);

        // 存储校验码，用于登录时校验，实际根据具体情况去做存储
        sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY_SMS,imageCode);

    }




    @GetMapping("/validateRememberMe")
    public Object validateRememberMe(){

        return "登录成功后，重启服务端让服务端丢失session，访问validateRememberMe接口查看是否能记住session";
    }

}
